package com.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javabean.User;
import com.model.DataBase;
//import com.model.RequestAttribute;
import com.model.UserService;

/**
 * Servlet implementation class UserCheck
 */
@WebServlet("/UserDeal")
public class UserDeal extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserDeal() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		UserService us=new UserService();//提供服务的model
		String flag=request.getParameter("flag");
		
		if(flag.equals("check")){
			//验证用户名和密码  isRight用于检测用户密码是否正确
			String userName=request.getParameter("userName");
			String userPassword=request.getParameter("userPassword");
			/*
			long userId=0;
			String userDepartment="";
			String userOffice="";
			String userDescription="";
			
			String sql="select * from user where userName='" +userName +"'";
			*/
			try {
				/*
				String dbpassword="";
				Connection con = DataBase.getConnection();
		        Statement stat=con.createStatement();
		        ResultSet rs=stat.executeQuery(sql);
		        while(rs.next()){
		        	dbpassword=rs.getString("userPassword");
		        	userId=rs.getLong("UserId");
		        	userDepartment=rs.getString("UserDepartment");
		        	userOffice=rs.getString("UserOffice");
		        	userDescription=rs.getString("UserDescription");
		        	userGrade=rs.getInt("UserGrade");
		        	userName=rs.getString("userName");
		        }*/
				User user = new User();
				user = us.getUserByName(userName);
				String dbpassword = user.getUserPassword();
		        if(dbpassword.equals("")||dbpassword == null){
		        	response.sendRedirect("Dlogin.jsp?flag=WrongName");
					return ;
		        }
				if(userPassword.equals(dbpassword))
				{
					
					//如果密码正确,则在session中摄入用户 的等级 
					request.getSession(true).setAttribute("user", user);
					request.getSession(true).setMaxInactiveInterval(3600);
				}else{
					response.sendRedirect("Dlogin.jsp?flag=WrongPassword");
					return ;
				}
			    response.sendRedirect("files/index.jsp");
			} catch(Exception e){
				e.printStackTrace();
				return;
			}
		}else if(flag.equals("register")){
			String userName = request.getParameter("userName");
			String userPassword = request.getParameter("userPassword");
			String userEmail = request.getParameter("userEmail");
			try{
				us.registerUser(userName, userPassword, userEmail);
				response.sendRedirect("Dlogin.jsp");
				return;
			}catch(Exception e){
				e.printStackTrace();
				return;
			}
		}
		/*
		else if(flag.equals("check_meeting")){
			//验证用户名和密码  isRight用于检测用户密码是否正确
			String userNumber=request.getParameter("userNumber");
			String userPassword=request.getParameter("userPassword");
			String ReserveDate=request.getParameter("ReserveDate");
			long userId=0;
			String userDepartment="";
			String userOffice="";
			String userDescription="";
			String userName="";
			
			String sql="select * from user where userNumber='" +userNumber +"'";
			int userGrade=1;//用户的级别 默认普通用户,该变量用于页面跳转的选择 
			try {
				String dbpassword="";
				Connection con = DataBase.getConnection();
		        Statement stat=con.createStatement();
		        ResultSet rs=stat.executeQuery(sql);
		        while(rs.next()){
		        	dbpassword=rs.getString("userPassword");
		        	userId=rs.getLong("UserId");
		        	userDepartment=rs.getString("UserDepartment");
		        	userOffice=rs.getString("UserOffice");
		        	userDescription=rs.getString("UserDescription");
		        	userGrade=rs.getInt("UserGrade");
		        	userName=rs.getString("userName");
		        }
		        if(dbpassword.equals("")){
		        	System.out.println("用户名错误："+ReserveDate);
		        	response.sendRedirect("meetBooking2.jsp?Loginflag=WrongName&ReserveDate="+ReserveDate);
					con.close();
					return ;
		        }
				if(userPassword.equals(dbpassword))
				{
					
					//如果密码正确,则在session中摄入用户 的等级 
					User user=new User();
					user.setUserId(userId);
					user.setUserDepartment(userDepartment);
					user.setUserDescription(userDescription);
					user.setUserOffice(userOffice);
					user.setUserName(userName);
					user.setUserGrade(userGrade);
					user.setUserPassword(userPassword);
					user.setUserNumber(userNumber);
					request.getSession(true).setAttribute("user", user);
					request.getSession(true).setMaxInactiveInterval(3600);
				}else{
					System.out.println("密码错误："+ReserveDate);
					response.sendRedirect("meetBooking2.jsp?Loginflag=WrongPassword&ReserveDate="+ReserveDate);
					con.close();
					return ;
				}
				//close work
				con.close();
				System.out.println("登录成功："+ReserveDate);
				request.getSession(true).setAttribute("meetRoom", "login");
			    response.sendRedirect("meetBooking2.jsp?Loginflag=Right&ReserveDate="+ReserveDate);
			} catch (SQLException e2) {
				e2.printStackTrace();
				return;
			}
		}
		else if(flag.equals("changePassword")){
			//修改用户密码 oldUserPassword newUserPassword confirmPassword
			User user=(User)request.getSession(true).getAttribute("user");
			String oldUserPassword=request.getParameter("oldUserPassword");
			String newUserPassword=request.getParameter("newUserPassword");
			String confirmPassword=request.getParameter("confirmPassword");
			String userNumber=((User)request.getSession(true).getAttribute("user")).getUserNumber();
			String userDBPassword=null;
			try {
				Connection con = DataBase.getConnection();
		        String sql = "SELECT UserPassword FROM user WHERE UserNumber=?";
		        PreparedStatement pstmt=con.prepareStatement(sql);
		        pstmt.setString(1, userNumber);
	        	ResultSet rs = pstmt.executeQuery();
	        	if( rs.next() ) {
	        		userDBPassword=rs.getString(1);
	        	}
	        	else {
	        		response.sendRedirect("UserDBError.jsp");
	        	}

				//close work
				con.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
				return;
			}
			
			
			if(!userDBPassword.equals(oldUserPassword)){
				response.sendRedirect("UserPas.jsp?flag=wrong");
				return ;
			}else if(!newUserPassword.equals(confirmPassword)){
				response.sendRedirect("UserPas.jsp?flag=notequal");
				return ;
			}
			String sql="update campus_information.user set UserPassword='"+newUserPassword +"' where userNumber='"+user.getUserNumber() +"'";
			try {
				Connection con = DataBase.getConnection();
		        Statement stat=con.createStatement();
		        int Rs=stat.executeUpdate(sql);
		        if(Rs==1){
		        	response.sendRedirect("UserPas.jsp?flag=good");
		        }
		   
				//close work
				con.close();
			} catch (SQLException e2) {
				e2.printStackTrace();
				return;
			}
		}
		else if(flag.equals("changeUser")){
			//url:User_BJ.jsp
			
			//用户的权限设置
			String[] userGrades;
			int userGrade=0;
			userGrades = request.getParameterValues("checkbox");
			if(userGrades!=null){
				for(int i=0;i<userGrades.length;i++){
					if(userGrades[i]!=null){
						if(userGrades[i].equals("car")){
							userGrade+=0x01;
						}
						else if(userGrades[i].equals("item")){
							userGrade+=0x02;
						}
						else if(userGrades[i].equals("device")){
							userGrade+=0x04;
						}
						else if(userGrades[i].equals("meetingroom")){
							userGrade+=0x08;
						}
					}
				}
			}
			String userName=request.getParameter("userName");
			
			int userId=Integer.parseInt(request.getParameter("userId"));
			String userDepartment=request.getParameter("userDepartment");
			String userOffice=request.getParameter("userOffice");
			//String userDescription=request.getParameter("userDescription");
			String userDescription = request.getParameter("userDescription");
			String userPassword=request.getParameter("userPassword");
			User user=new User();
			user.setUserId(userId);
			user.setUserDepartment(userDepartment);
			user.setUserDescription(userDescription);
			user.setUserOffice(userOffice);
			user.setUserName(userName);
			user.setUserGrade(userGrade);
			user.setUserPassword(userPassword);
			boolean isSucceed=us.changeUser(user);
			if(isSucceed){
				response.sendRedirect("User.jsp");
			}
			else
				response.sendRedirect("error.jsp");			
		}
		else if(flag.equals("pageChange")){
			String pageChange=request.getParameter("pageChange");
			request.setAttribute("pageChange", pageChange+"");
			request.getRequestDispatcher("User.jsp").forward(request, response);			
			
		}
		else if(flag.equals("changeMyself")){
			//url:UserMes.jsp
			
			String userName=request.getParameter("userName");
			String userNumber=request.getParameter("userNumber");
			
			int userGrade=Integer.parseInt(request.getParameter("userGrade"));
			int userId=Integer.parseInt(request.getParameter("userId"));
			String userDepartment=request.getParameter("userDepartment");
			String userOffice=request.getParameter("userOffice");
			String userDescription = request.getParameter("userDescription");
			String userPassword=request.getParameter("userPassword");
			
			User user=new User();
			user.setUserId(userId);
			
			user.setUserDepartment(userDepartment);
			user.setUserDescription(userDescription);
			user.setUserOffice(userOffice);
			user.setUserName(userName);
			user.setUserGrade(userGrade);
			user.setUserPassword(userPassword);
			user.setUserNumber(userNumber);
			boolean isSucceed=us.changeUser(user);
			if(isSucceed){
				request.getSession(true).removeAttribute("user");
				request.getSession(true).setAttribute("user", user);
				request.getSession(true).setMaxInactiveInterval(3600);
				response.sendRedirect("UserMes.jsp");
			}
			
		}else if(flag.equals("userDelete")){

			String[] userNumbers;
			userNumbers = request.getParameterValues("userNumbers");
			
			if( userNumbers==null ) {
				response.sendRedirect("error.jsp");
				return;
			}
			
			//Connect DB
			try {
				Connection con = DataBase.getConnection();
				PreparedStatement pstmtDel = con.prepareStatement("DELETE FROM campus_information.user WHERE UserNumber=?");
				for(int i=0; i<userNumbers.length; i++) {
					pstmtDel.setString(1, userNumbers[i]);
					pstmtDel.execute();
				}
				con.close();
				response.sendRedirect("User.jsp");
				return;
			} catch (SQLException e2) {
				e2.printStackTrace();
				response.sendRedirect("error.jsp");
				return;
			}
		}else if(flag.equals("addUser")){
			String userNumber=request.getParameter("userNumber");
			String userName=request.getParameter("userName");
			// set the user's authorities
			String[] userGrades;
			int userGrade=0;
			userGrades = request.getParameterValues("checkbox");
			if(userGrades!=null){
				for(int i=0;i<userGrades.length;i++){
					if(userGrades[i]!=null){
						if(userGrades[i].equals("car")){
							userGrade+=0x01;
						}
						else if(userGrades[i].equals("item")){
							userGrade+=0x02;
						}
						else if(userGrades[i].equals("device")){
							userGrade+=0x04;
						}
						else if(userGrades[i].equals("meetingroom")){
							userGrade+=0x08;
						}
					}
				}
			}
			String userDepartment=request.getParameter("userDepartment");
			String userOffice=request.getParameter("userOffice");
			String userDescription = request.getParameter("userDescription");
			if(userName.length()==0 || userNumber.length()==0)
			{
				response.sendRedirect("User.jsp");
				return;
			}
			User user=new User();
			user.setUserName(userName);
			user.setUserPassword(userNumber);
			user.setUserNumber(userNumber);
			user.setUserOffice(userOffice);
			user.setUserDepartment(userDepartment);
			user.setUserGrade(userGrade);
			user.setUserDescription(userDescription);
			
			if(us.addUser(user)){
				response.sendRedirect("User.jsp");
				return ;
			}else{
				response.sendRedirect("error.jsp");
			}
		}else if(flag.equals("changeGrade")){
			int userGrade=Integer.parseInt(request.getParameter("userGrade"));
			String userName=((User)request.getSession().getAttribute("user")).getUserName();
			if(us.changeGrade(userGrade, userName)){
				response.sendRedirect("User.jsp");//修改成功
				return ;
			}else{
				response.sendRedirect("error.jsp");
			}
		}else{
			response.sendRedirect("error.jsp");
		}
		;
		*/
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}